Timers and Progress Bars

Objectives


Discussion

Timers

Progress Bar

NumericUpDown Box

Back to top


Demonstration

In this demo we will create a timer form. It will allow the user to select a time period and start the timer.  When the time reaches the selected period the timer will stop and a messagebox will appear.  Additionally a progress bar will show the progress.

1.  Add a new form to your project.  Add a button (btnStart), a numericupdown control (nudTime), a timer (timer1), and a progressbar (pbTime).

2.  In the click event for btnStart, add the following code. This code sets the value of the progress bar to 0, sets the maximum possible value of the progress bar to the value selected in the numericupdown control, and starts the timer.

pbTime.Value = 0
pbTime.Maximum = nudTime.Value
Timer1.Enabled = True

3.  In the tick event for the timer add the following code.  If you double-click the timer control the tick event will show up in the code window.  The following code first checks to see if the progress bar has reached its maximum value. If so, then the timer is stopped and a messagebox is displayed indicating that time is up.  If the maximum value has not been reached, the value of the progress bar is incremented.

If pbTime.Value = pbTime.Maximum Then
   Timer1.Enabled = False
MessageBox.Show("Times up")
Else
   pbTime.Value = pbTime.Value + 1
End If

4.  Run the program and experiment with it. Study the code. 

5.  Experiment with the properties of the timer.  Change the interval to other values such as 100 and 10000.

6.  Experiment with the properties of the progress bar and the numericupdown control. 

7.  What happens if you comment out the line "pbTime.value = 0". Comment it out and run the program.  Click the button several times.

Back to top
Exercises

1.  Write a program that requires the user to guess a secret code.  The image below shows the GUI for the program.  When the form loads the timer starts and the time in seconds is displayed in the status bar.  In the image below, time is currently 7.  The user must then select a number in each NumericUpDown control and click the button.  The program compares what the user selected with a "secret" code.  In this program the secret code is 1,2,3.  The program checks the user's guess and "displays the number correct" in the progress bar.  In this case, 2 out of 3 are correct so the progress bar is two-thirds full.  Once the user guesses the secret code the numericUpdown controls are disabled and the timer stops.  in this example the range of the NumericUpDown controls was set to 1 to 3.  You can set the range higher but it will make the game progrssively more difficult.  Later we will learn how to generate random numbers so that the secret code would change each time you played.  If you are interested look up "rnd()" in help and check out the example.

     

Back to top
Links & Help
Back to top